<template>
  <div class="supplier-prices-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">供应商价格管理</span>
          <div class="header-actions">
            <ImportButton 
              data-type="supplier-prices" 
              @import-success="handleImportSuccess"
            />
            <ExportButton
              :data="tableData"
              :columns="exportColumns"
              filename="供应商价格"
            />
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增报价
            </el-button>
            <el-button type="success" @click="handleCompare">
              <el-icon><DataAnalysis /></el-icon>
              价格对比
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="供应商">
          <el-input v-model="searchForm.supplierName" placeholder="请输入供应商名称" clearable />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="searchForm.materialName" placeholder="请输入物料名称" clearable />
        </el-form-item>
        <el-form-item label="报价状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" value="pending" />
            <el-option label="已生效" value="active" />
            <el-option label="已过期" value="expired" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 批量操作 -->
      <div v-if="selectedRows.length > 0" class="batch-actions">
        <el-alert :title="`已选择 ${selectedRows.length} 项`" type="info" :closable="false">
          <template #default>
            <div class="batch-buttons">
              <el-button size="small" type="success" @click="handleBatchApprove">批量审核</el-button>
              <el-button size="small" type="warning" @click="handleBatchReject">批量拒绝</el-button>
              <el-button size="small" type="danger" @click="handleBatchDelete">批量删除</el-button>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="supplierName" label="供应商" width="180" />
        <el-table-column prop="supplierCode" label="供应商编码" width="150" />
        <el-table-column prop="materialCode" label="物料编码" width="150" />
        <el-table-column prop="materialName" label="物料名称" width="180" />
        <el-table-column prop="spec" label="规格" width="150" />
        <el-table-column prop="price" label="报价" width="120">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: bold; font-size: 16px;">
              ¥{{ row.price.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="minOrderQty" label="起订量" width="100" />
        <el-table-column prop="deliveryDays" label="交期(天)" width="100" />
        <el-table-column prop="validFrom" label="有效期开始" width="120" />
        <el-table-column prop="validTo" label="有效期结束" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === 'pending'" 
              link 
              type="success" 
              @click="handleApprove(row)"
            >
              审核
            </el-button>
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="info" @click="handleViewDetail(row)">详情</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="800px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商编码" prop="supplierCode">
              <el-input v-model="form.supplierCode" placeholder="请输入供应商编码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="spec">
              <el-input v-model="form.spec" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报价" prop="price">
              <el-input-number 
                v-model="form.price" 
                :min="0" 
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="币种" prop="currency">
              <el-select v-model="form.currency" style="width: 100%">
                <el-option label="人民币(CNY)" value="CNY" />
                <el-option label="美元(USD)" value="USD" />
                <el-option label="欧元(EUR)" value="EUR" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="起订量" prop="minOrderQty">
              <el-input-number 
                v-model="form.minOrderQty" 
                :min="1" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货期(天)" prop="deliveryDays">
              <el-input-number 
                v-model="form.deliveryDays" 
                :min="1" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="有效期开始" prop="validFrom">
              <el-date-picker
                v-model="form.validFrom"
                type="date"
                placeholder="选择开始日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期结束" prop="validTo">
              <el-date-picker
                v-model="form.validTo"
                type="date"
                placeholder="选择结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="付款方式" prop="paymentTerms">
          <el-input v-model="form.paymentTerms" placeholder="例如：30天账期" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 价格对比对话框 -->
    <el-dialog 
      v-model="compareDialogVisible" 
      title="供应商价格对比"
      width="1200px"
    >
      <div class="compare-header">
        <el-form :inline="true">
          <el-form-item label="选择物料">
            <el-select v-model="compareMaterial" placeholder="请选择物料" style="width: 300px">
              <el-option label="OLED屏幕" value="MAT002" />
              <el-option label="A17芯片" value="MAT003" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLoadCompare">对比</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="compareData" border stripe>
        <el-table-column prop="supplierName" label="供应商" width="180" />
        <el-table-column prop="price" label="报价" width="120">
          <template #default="{ row }">
            <span :style="{ 
              color: row.isLowest ? '#67c23a' : '#f56c6c', 
              fontWeight: 'bold',
              fontSize: '16px'
            }">
              ¥{{ row.price.toFixed(2) }}
              <el-tag v-if="row.isLowest" type="success" size="small">最低价</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="minOrderQty" label="起订量" width="100" />
        <el-table-column prop="deliveryDays" label="交期(天)" width="100" />
        <el-table-column prop="paymentTerms" label="付款方式" width="150" />
        <el-table-column prop="validTo" label="有效期至" width="120" />
        <el-table-column prop="quality" label="质量评级" width="120">
          <template #default="{ row }">
            <el-rate v-model="row.quality" disabled />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleSelectSupplier(row)">
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, DataAnalysis } from '@element-plus/icons-vue'
import ImportButton from '@/components/common/ImportButton.vue'
import ExportButton from '@/components/common/ExportButton.vue'

// 搜索表单
const searchForm = reactive({
  supplierName: '',
  materialName: '',
  status: ''
})

// 选中的行
const selectedRows = ref([])

// 导出列配置
const exportColumns = [
  { prop: 'supplierName', label: '供应商' },
  { prop: 'materialCode', label: '物料编码' },
  { prop: 'materialName', label: '物料名称' },
  { prop: 'price', label: '报价' },
  { prop: 'minOrderQty', label: '起订量' },
  { prop: 'deliveryDays', label: '交期' }
]

// 表格数据
const tableData = ref([
  {
    id: 1, supplierName: '三星显示', supplierCode: 'SUP001',
    materialCode: 'MAT002', materialName: 'OLED屏幕', spec: '6.1英寸',
    unit: '片', price: 800, minOrderQty: 100, deliveryDays: 15,
    validFrom: '2024-01-01', validTo: '2024-12-31',
    paymentTerms: '30天账期', status: 'active'
  },
  {
    id: 2, supplierName: 'LG Display', supplierCode: 'SUP002',
    materialCode: 'MAT002', materialName: 'OLED屏幕', spec: '6.1英寸',
    unit: '片', price: 780, minOrderQty: 200, deliveryDays: 20,
    validFrom: '2024-01-01', validTo: '2024-12-31',
    paymentTerms: '45天账期', status: 'pending'
  },
  {
    id: 3, supplierName: 'TSMC', supplierCode: 'SUP003',
    materialCode: 'MAT003', materialName: 'A17芯片', spec: '3nm工艺',
    unit: '颗', price: 1200, minOrderQty: 500, deliveryDays: 30,
    validFrom: '2024-01-01', validTo: '2024-12-31',
    paymentTerms: '60天账期', status: 'active'
  }
])

// 价格对比数据
const compareData = ref([
  {
    supplierName: '三星显示', price: 800, minOrderQty: 100, 
    deliveryDays: 15, paymentTerms: '30天账期', validTo: '2024-12-31',
    quality: 5, isLowest: false
  },
  {
    supplierName: 'LG Display', price: 780, minOrderQty: 200, 
    deliveryDays: 20, paymentTerms: '45天账期', validTo: '2024-12-31',
    quality: 4, isLowest: true
  },
  {
    supplierName: 'BOE', price: 820, minOrderQty: 150, 
    deliveryDays: 18, paymentTerms: '30天账期', validTo: '2024-12-31',
    quality: 4, isLowest: false
  }
])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 3
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增报价')
const compareDialogVisible = ref(false)
const formRef = ref(null)
const compareMaterial = ref('')

// 表单数据
const form = reactive({
  id: null,
  supplierName: '',
  supplierCode: '',
  materialCode: '',
  materialName: '',
  spec: '',
  unit: '',
  price: 0,
  currency: 'CNY',
  minOrderQty: 1,
  deliveryDays: 1,
  validFrom: '',
  validTo: '',
  paymentTerms: '',
  remark: ''
})

// 表单验证规则
const rules = {
  supplierName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
  materialCode: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
  materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入报价', trigger: 'blur' }],
  validFrom: [{ required: true, message: '请选择有效期开始日期', trigger: 'change' }],
  validTo: [{ required: true, message: '请选择有效期结束日期', trigger: 'change' }]
}

// 获取状态标签
const getStatusTag = (status) => {
  const tagMap = {
    pending: 'warning',
    active: 'success',
    expired: 'info',
    rejected: 'danger'
  }
  return tagMap[status] || ''
}

// 获取状态名称
const getStatusName = (status) => {
  const nameMap = {
    pending: '待审核',
    active: '已生效',
    expired: '已过期',
    rejected: '已拒绝'
  }
  return nameMap[status] || status
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.supplierName = ''
  searchForm.materialName = ''
  searchForm.status = ''
  handleSearch()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 批量操作
const handleBatchApprove = () => {
  ElMessage.success('批量审核成功')
  selectedRows.value = []
}

const handleBatchReject = () => {
  ElMessage.success('批量拒绝成功')
  selectedRows.value = []
}

const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条报价吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量删除成功')
    selectedRows.value = []
  })
}

// 导入成功回调
const handleImportSuccess = (result) => {
  ElMessage.success(`成功导入 ${result.validRows} 条数据`)
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增报价'
  Object.assign(form, {
    id: null,
    supplierName: '',
    supplierCode: '',
    materialCode: '',
    materialName: '',
    spec: '',
    unit: '',
    price: 0,
    currency: 'CNY',
    minOrderQty: 1,
    deliveryDays: 1,
    validFrom: '',
    validTo: '',
    paymentTerms: '',
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑报价'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 提交
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('提交:', form)
      ElMessage.success(form.id ? '修改成功' : '新增成功')
      dialogVisible.value = false
      handleSearch()
    }
  })
}

// 审核
const handleApprove = (row) => {
  ElMessageBox.confirm(`确定要审核通过该报价吗？`, '审核确认', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('审核通过')
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除该报价吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

// 查看详情
const handleViewDetail = (row) => {
  ElMessage.info('查看详情功能')
}

// 价格对比
const handleCompare = () => {
  compareDialogVisible.value = true
}

const handleLoadCompare = () => {
  ElMessage.success('加载价格对比数据')
}

const handleSelectSupplier = (row) => {
  ElMessage.success(`已选择供应商: ${row.supplierName}`)
  compareDialogVisible.value = false
}
</script>

<style scoped>
.supplier-prices-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.batch-actions {
  margin-bottom: 20px;
}

.batch-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.compare-header {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>

